package com.torfox.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;

import com.torfox.services.ServiceException;

/**
* <code>CheckPropertyPlaceHolder</code> handles multiple property files
*
* @version $Revision: $ by $Author: $
*/
public class GeneralPropertyPlaceHolder extends PropertyPlaceholderConfigurer
{
	private static final Logger log = LoggerFactory.getLogger(GeneralPropertyPlaceHolder.class);

	private final static String ENV_PROPERTY_KEY = "env";

	private Properties _properties = null;

	private String _locationPath = null;

	/**
	 *
	 *@param resorce get from Spring
	 * @throws ServiceException
	 *
	 */
	public GeneralPropertyPlaceHolder(final Resource resource) throws IOException, ServiceException
	{
		super();
		_locationPath = resource.getFile().getAbsolutePath();
		loadProperties();
		setSystemEnvironments();
	}

	private void loadProperties() throws IOException
	{
		FileInputStream inputStream = null;
		try
		{
			_properties = new Properties();
			inputStream = new FileInputStream(_locationPath);
			_properties.load(inputStream);
		}
		finally
		{
			if (inputStream != null)
			{
				inputStream.close();
			}
		}
	}

	/**
	 * Set environments to JVM System properties
	 * @throws ServiceException
	 */
	private void setSystemEnvironments() throws ServiceException
	{
		if (_properties != null && !_properties.isEmpty())
		{
			String envValue;
			if (System.getProperty("env") != null)
			{
				envValue = System.getProperty("env");
				log.info("Using {} environment", envValue);
			}
			else
			{
				final String env = _properties.getProperty(
				                GeneralPropertyPlaceHolder.ENV_PROPERTY_KEY);
				if (env == null)
				{
					GeneralPropertyPlaceHolder.log.error(
					        "Could not find obligatory '{}' property. This property must be set to run application!",
					        GeneralPropertyPlaceHolder.ENV_PROPERTY_KEY);
					throw new ServiceException("No environment property set");
				}
				envValue = System.getenv(env);
				if (envValue == null)
				{
					GeneralPropertyPlaceHolder.log.error(
					        "Could not locate '{}' system variable. This property must be set to run application!",
					        env);
					throw new ServiceException("No environment set");
				}
				log.info("Using {} environment", envValue);
			}
			System.setProperty(GeneralPropertyPlaceHolder.ENV_PROPERTY_KEY, envValue);
		}
		else
		{
			throw new ServiceException("No environment set. Use -Denv=some_name to set environment");
		}

	}
}